package org.example.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 用于生成和解析JWT
 */
public class JWTUtils {

    //    声明一个密钥
    private static final String SECRET_KEY = "dewishyi";

    // 生成JWT
    public String createToken(Integer userId, String username, List<String> auth) {
        Date currentDate = new Date();
        Date expTime = new Date(currentDate.getTime() + (1000 * 60 * 5));
        // 组装头数据
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("alg", "HS256");
        headMap.put("typ", "JWT");
        return JWT.create()
                .withHeader(headMap)// 头部信息
                .withClaim("userId", userId) //自定义信息
                .withClaim("username", username)
                .withClaim("auth", auth)
                .withIssuedAt(currentDate) //创建和过期时间
                .withExpiresAt(expTime)
                .sign(Algorithm.HMAC256(SECRET_KEY)); //签名
    }


    // 解析并验证JWT
    public static Boolean verifyToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 从JWT中获取相关信息
    public Integer getUserId(String token){
        try{
            // 使用秘钥创建一个解析对象
            JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
            //验证JWT
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            Claim userId = decodedJWT.getClaim("userId");
            return userId.asInt();
        }catch (TokenExpiredException e){
            e.printStackTrace();
        }
        return null;
    }
}
